from datetime import datetime
from typing import List, Optional
from sqlalchemy import func
from sqlalchemy.orm import Session

from src.database.models import DHTNode, InfoHash
from src.database.database import Database
from src.routing.routing_table import Node
from src.log.logger import setup_logger

class DHTRepository:
    """DHT数据仓库"""
    
    def __init__(self):
        self.db = Database.get_instance()
        self.logger = setup_logger("dht_repository")
        
    def save_node(self, node: Node) -> None:
        """保存节点信息
        
        Args:
            node: DHT节点
        """
        try:
            with self.db.get_session() as session:
                node_record = session.query(DHTNode).filter(
                    DHTNode.node_id == node.node_id.hex()
                ).first()
                
                if node_record:
                    # 更新现有节点
                    node_record.last_active = datetime.utcnow()
                    node_record.is_active = True
                else:
                    # 创建新节点记录
                    node_record = DHTNode(
                        node_id=node.node_id.hex() if node.node_id else None,
                        ip=node.ip,
                        port=node.port,
                    )
                    session.add(node_record)
                    
        except Exception as e:
            self.logger.error(f"保存节点失败: {e}", exc_info=True)
            raise
            
    def update_node_status(self, node: Node, success: bool) -> None:
        """更新节点状态
        
        Args:
            node: DHT节点
            success: 操作是否成功
        """
        try:
            with self.db.get_session() as session:
                node_record = session.query(DHTNode).filter(
                    DHTNode.node_id == node.node_id.hex()
                ).first()
                
                if node_record:
                    if success:
                        node_record.success_count += 1
                    else:
                        node_record.failed_count += 1
                    node_record.last_active = datetime.utcnow()
                    
        except Exception as e:
            self.logger.error(f"更新节点状态失败: {e}", exc_info=True)
            
    def save_info_hash(self, info_hash: bytes) -> None:
        """保存info_hash
        
        Args:
            info_hash: 资源hash值
        """
        try:
            with self.db.get_session() as session:
                hash_hex = info_hash.hex()
                hash_record = session.query(InfoHash).filter(
                    InfoHash.info_hash == hash_hex
                ).first()
                
                if hash_record:
                    # 更新现有记录
                    hash_record.last_seen = datetime.utcnow()
                    hash_record.announce_count += 1
                else:
                    # 创建新记录
                    hash_record = InfoHash(info_hash=hash_hex)
                    session.add(hash_record)
                    
        except Exception as e:
            self.logger.error(f"保存info_hash失败: {e}", exc_info=True) 